<template>
    <div class="main">
        <el-upload
        class="upload-demo"
        action="https://jsonplaceholder.typicode.com/posts/"
        :beforeUpload="beforeAvatarUpload"
        multiple
        accept=".xlsx, .xls"
        >
            <el-link :underline="false" icon="el-icon-upload2">导入excel文件</el-link>
        </el-upload>
    </div>
</template>
<style lang="less" scoped>
.main {
  margin-left: 250px;
}
.el-link{
    font-size: 20px;
}
</style>
<script>
import XLSX from 'xlsx'
export default {
    name:'Uploads',
    data(){
        return{
            tableData:[]
        }
    },
    methods:{
      beforeAvatarUpload(file) { 
            const fileReader = new FileReader()
            fileReader.onload = (ev) => {
                try {
                    const data = ev.target.result
                    const workbook = XLSX.read(data, {
                    type: 'binary' // 以字符编码的方式解析
                    })
                    const exlname = workbook.SheetNames[0] // 取第一张表
                    const exl =XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
                    // 将 JSON 数据挂到 data 里
                    for(let key=1;key<exl.length;key++){
                        let json={};
                        json["serial_Number"]=exl[key].__EMPTY;
                        json["barcode"]=exl[key].__EMPTY_1;
                        json["goods_Name"]=exl[key].__EMPTY_2;
                        json["unit"]=exl[key].__EMPTY_3;
                        json["type"]=exl[key].__EMPTY_4;
                        this.tableData.push(json)
                    }
                    // document.getElementsByName('file')[0].value = '' // 根据自己需求，可重置上传value为空，允许重复上传同一文件
                } catch (e) {
                    console.log('出错了：：')
                    return false
                }
            }
            fileReader.readAsBinaryString(file)
      },
    //   open(){
    //       this.$refs.file.dispatchEvent(new MouseEvent('click'));
    //   },
    },
    watch:{
        tableData:function (params) {
            this.$emit('fn',params);
        }
    }
}
</script>

